package com.haipumi.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;

import com.google.gson.Gson;
import com.haipumi.beans.IndexTaskData;
import com.haipumi.beans.JsonModel;
import com.haipumi.beans.haipumi_product;
import com.haipumi.beans.haipumi_reply;
import com.haipumi.beans.haipumi_task;
import com.haipumi.beans.haipumi_taskType;
import com.haipumi.beans.haipumi_user;
import com.haipumi.biz.TaskBiz;
import com.haipumi.biz.impl.TaskBizImpl;
import com.haipumi.utils.CommonData;
import com.haipumi.utils.FileUploadUtil;
import com.haipumi.utils.RequestUtil;
import com.haipumi.utils.YcStringUtils;

public class TaskServlet extends CommonServlet {

	private static final long serialVersionUID = -2137842246451059461L;
	private TaskBiz tb=new TaskBizImpl();
	private static String STATICttid;
	private static String STATIClimit;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String op=request.getParameter("op");
		if(op!=null){
			if("findTask".equals(op)){
				findTaskOp(request,response);
			}else if("indexFindTask".equals(op)){
				indexFindTaskOp(request,response);
			}else if("indexTaskForm".equals(op)){
				indexTaskFormOp(request,response);
			}else if("findTaskReply".equals(op)){
				findTaskReplyOp(request,response);
			}else if("addTaskReply".equals(op)){
				addTaskReplyOp(request,response);
			}else if("acceptTask".equals(op)){
				acceptTaskOp(request,response);
			}else if("careTask".equals(op)){
				careTaskOp(request,response);
			}else if("shieldTask".equals(op)){
				shieldTaskOp(request,response);
			}else if("operateTask".equals(op)){
				operateTaskOp(request,response);
			}else if("taskdetail".equals(op)){
				taskdetailOp(request,response);
			}
		}else{
			//必须要登陆,才能上传图片的判断
			haipumi_user user=(haipumi_user) request.getSession().getAttribute(CommonData.USERSESSION);
			if( judgeIsLogin(user,response) ){
				return;
			}
			//TODO	图片保存的位置修改
			Map<String,List<String>> pvalues=commonUpload(request,response,"images/taskPhoto/");
			List<String> ops=pvalues.get("op");
			op=ops.get(0);
			if(op!=null){
				if("taskphotoupload".equals(op)){
					taskphotouploadOp(pvalues,request,response);
				}
			}
		}
	}

	//查看任务详情
	private void taskdetailOp(HttpServletRequest request,
			HttpServletResponse response) {
		String tid=request.getParameter("tid");
		if(tid.indexOf(":")>0){
			String[] tids=tid.split(":");
			if(tids.length>2){
				tid=tids[2];
			}
		}
		if(tid==null || "".equals(tid)){
			tid="0";
		}
		List<IndexTaskData> list=tb.findNewTask(tid,"-1","0","0","");
		if(list.get(0)!=null){
			list.get(0).setTsendtime(list.get(0).getTsendtime().substring(0, 10));
			request.setAttribute(CommonData.DETAILSESSION, list.get(0));
			try {
				request.getRequestDispatcher("details.jsp").forward(request, response);
			} catch (ServletException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	//对任务进行操作
	private void operateTaskOp(HttpServletRequest request,
			HttpServletResponse response) {
		haipumi_user user=(haipumi_user) request.getSession().getAttribute(CommonData.USERSESSION);
		if( judgeIsLogin(user,response) ){
			return;
		}
		String status=request.getParameter("status");
		String tid=request.getParameter("tid");
		int falg=tb.operateTask(tid,status,user);
		JsonModel jm=new JsonModel();
		if(falg>0){
			jm.setCode(1);
		}else{
			jm.setMsg("操作失败,请重试");
		}
		super.outData(response, jm);
	}

	//任务里面的图片上传
	private void taskphotouploadOp(Map<String, List<String>> pvalues,
			HttpServletRequest request, HttpServletResponse response) {
		String tphoto=pvalues.get("newfphoto").get(1);//0为图片原名称  1为图片修改后的名称
		JsonModel jm=new JsonModel();
		jm.setCode(1);
		jm.setObj(tphoto);
		super.outData(response, jm);
	}

	//屏蔽任务
	private void shieldTaskOp(HttpServletRequest request,
			HttpServletResponse response) {
		haipumi_user user=(haipumi_user) request.getSession().getAttribute(CommonData.USERSESSION);
		if( judgeIsLogin(user,response) ){
			return;
		}
		String tid=request.getParameter("tid");
		String status=request.getParameter("status");//为了判断是取消屏蔽,还是添加屏蔽
		int flag=tb.shieldTask(user,tid,status);
		JsonModel jm=new JsonModel();
		if(flag>0){
			jm.setCode(1);
		}else{
			jm.setCode(0);
			if(flag==-1){
				//表示已经屏蔽过了
				jm.setMsg("请勿重复屏蔽任务!");
			}else if(flag==-2){
				//表示自己屏蔽自己
				jm.setMsg("不能屏蔽自己!");
			}else{
				jm.setMsg("屏蔽失败,请和客服联系!");
			}
		}
		super.outData(response, jm);
	}

	//关注任务
	private void careTaskOp(HttpServletRequest request,
			HttpServletResponse response) {
		haipumi_user user=(haipumi_user) request.getSession().getAttribute(CommonData.USERSESSION);
		if( judgeIsLogin(user,response) ){
			return;
		}
		String tid=request.getParameter("tid");
		String status=request.getParameter("status");
		String[] flag=tb.caretTask(user,tid,status);
		//0表示关注, 2表示取消关注 
		if("0".equals( flag[0] )){
			user.setUlike(Integer.toString( Integer.parseInt( user.getUlike() )+1 ));
		}else if("2".equals( flag[0] )){
			user.setUlike(Integer.toString( Integer.parseInt( user.getUlike() )-1 ));
		}
		request.getSession().setAttribute(CommonData.USERSESSION, user);
		JsonModel jm=new JsonModel();
		if(Integer.parseInt( flag[1] )>0){
			jm.setCode(1);
			jm.setObj(flag);
		}else{
			jm.setCode(0);
			jm.setMsg("关注任务失败!");
		}
		super.outData(response, jm);
	}

	//接收任务
	private void acceptTaskOp(HttpServletRequest request,
			HttpServletResponse response) {
		haipumi_user user=(haipumi_user) request.getSession().getAttribute(CommonData.USERSESSION);
		if( judgeIsLogin(user,response) ){
			return;
		}
		String tid=request.getParameter("tid");
		int flag=tb.acceptTask(user,tid);
		JsonModel jm=new JsonModel();
		if(flag>0){
			jm.setCode(1);
		}else{
			jm.setCode(0);
			jm.setMsg("不能够接受自己的任务");
		}
		super.outData(response, jm);
	}

	//添加任务评论信息
	private void addTaskReplyOp(HttpServletRequest request,
			HttpServletResponse response) {
		//没有登陆的情况下不允许添加评论
		haipumi_user user=(haipumi_user) request.getSession().getAttribute(CommonData.USERSESSION);
		if( judgeIsLogin(user,response) ){
			return;
		}
		haipumi_reply reply=RequestUtil.parseRequest(request, haipumi_reply.class);
		String rid=tb.addReply(reply,user);
		reply.setRid( rid );
		JsonModel jm=new JsonModel();
		if(rid!="-1"){
			jm.setCode(1);
			jm.setObj(reply);
		}else{
			jm.setCode(0);
			jm.setMsg("添加评论失败");
		}
		super.outData(response, jm);
	}

	//查询任务的评论信息
	private void findTaskReplyOp(HttpServletRequest request,
			HttpServletResponse response) {
		String tid=request.getParameter("tid");
		List<haipumi_reply> list=tb.findReply(tid);
		JsonModel jm=new JsonModel();
		jm.setCode(1);
		jm.setObj(list);
		super.outData(response, jm);
	}

	//发布任务
	private void indexTaskFormOp(HttpServletRequest request,
			HttpServletResponse response) {
		haipumi_user user=(haipumi_user) request.getSession().getAttribute(CommonData.USERSESSION);
		if (judgeIsLogin(user,response) ){
			return;
		}
		haipumi_task task=RequestUtil.parseRequest(request, haipumi_task.class);
		//获取期限时间字符串
		String tdate=request.getParameter("tdate");
		if("当天".equals(tdate)){
			Date date= new Date();//创建一个时间对象，获取到当前的时间
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//设置时间显示格式
			String str = sdf.format(date);//将当前时间格式化为需要的类型
			task.setTstarttime(str+" 00:00:00");
			task.setTendtime(str+" 23:59:59");
		}else{
			//裁剪传来的字符串,分出开始时间和结束时间
			String[] tdates=tdate.split("-");
			//开始时间
			String[] tstartDates=tdates[0].split("/");
			if(tstartDates.length<3){//防止空指针
				return;
			}
			//传来的格式 月/日/年
			task.setTstarttime("20"+tstartDates[2].trim()+"-"+tstartDates[0].trim()+"-"+tstartDates[1]+" 00:00:00");
			//结束时间
			String[] tendDates=tdates[1].split("/");
			task.setTendtime("20"+tendDates[2].trim()+"-"+tendDates[0].trim()+"-"+tendDates[1]+" 23:59:59");
		}
		task.setTmore(YcStringUtils.javascriptEscape( task.getTmore() ) );
		task.setTaddr(YcStringUtils.javascriptEscape( task.getTaddr() ) );
		IndexTaskData newTaskData=tb.addTask(task, user);
		//对求助信息条数进行处理
		user.setIssuecount(Integer.toString( Integer.parseInt( user.getIssuecount() )+1 ));
		request.getSession().setAttribute(CommonData.USERSESSION, user);
		
		JsonModel jm=new JsonModel();
		jm.setCode(1);
		jm.setObj(newTaskData);
		
		super.outData(response, jm);
	}

	//首页的任务查询
	private void indexFindTaskOp(HttpServletRequest request,
			HttpServletResponse response) {
		boolean readflag=false;//是否清空当前页面的数据
		haipumi_user user=(haipumi_user) request.getSession().getAttribute(CommonData.USERSESSION);//取到当前用户的id
		String uid="0";//0为游客查询
		if(user!=null){
			//表示为登陆状态
			uid=user.getUid();
			//需要判断,不刷出屏蔽的任务
		}
		String ttid=request.getParameter("ttid");
		String limit=request.getParameter("limit");
		String oldTask=(String) request.getSession().getAttribute(CommonData.READSESSION);
		String mark=request.getParameter("mark");
		//选择了其他类别,清空session的已阅数据
		if(!ttid.equals(STATICttid) || !limit.equals(STATIClimit) || "0".equals(mark)){
			oldTask=null;
			readflag=true;
		}
		if(oldTask==null){
			oldTask="";
		}
		STATIClimit=limit;
		STATICttid=ttid;
		List<IndexTaskData> list=tb.findNewTask("",uid,ttid,limit,oldTask);
		for(int i=0;i<list.size();i++){
			oldTask=oldTask+list.get(i).getTid()+",";
		}
		request.getSession().setAttribute(CommonData.READSESSION, oldTask);
		JsonModel jm=new JsonModel();
		if(list.size()==0){//如果没有数据
			jm.setCode(-1);
		}else{
			jm.setCode(1);
			jm.setObj(list);			
		}
		if(readflag){
			jm.setMsg("0");//清空标记
		}else{
			jm.setMsg("1");
		}
		super.outData(response, jm);
	}

	//查询已接受的任务 和 发布的 任务
	private void findTaskOp(HttpServletRequest request,
			HttpServletResponse response) {
		haipumi_user user=(haipumi_user) request.getSession().getAttribute(CommonData.USERSESSION);//取到当前用户的id
		if (judgeIsLogin(user,response) ){
			return;
		}
		String status=request.getParameter("status");
		String uid=user.getUid();
		List<haipumi_task> list=tb.findAllTask(uid,status);
		JsonModel jm=new JsonModel();
		jm.setCode(1);
		jm.setObj(list);
		super.outData(response, jm);
	}
	
	//是否登陆判断
	private boolean judgeIsLogin(haipumi_user user,HttpServletResponse response){
		boolean flag=false;
		if(user==null){
			flag=true;
			JsonModel jm=new JsonModel();
			jm.setCode(0);
			jm.setMsg("请先登录...");
			super.outData(response, jm);
		}
		return flag;
	}
	
	//通用上传封装
	private Map<String, List<String>> commonUpload(HttpServletRequest request,
			HttpServletResponse response, String fileAddress) {
		//这是商品图片上传文件时,用得方法是在http实体中包装参数,request已经没有用了,只能用smartupload取值
		//上传文件时,request已经没有用了
		Map<String ,List<String>> pvalues=null;
		PageContext pagecontext=javax.servlet.jsp.JspFactory.getDefaultFactory().getPageContext(this, request, response, null, true, 8192, true);
		FileUploadUtil fuu=new FileUploadUtil();
		try {
			pvalues=fuu.fileUpload(pagecontext, fileAddress);//通过传递过来的参数 保存相应的文件位置
		} catch (Exception e) {
			e.printStackTrace();
		}//完成图片上传
		return pvalues;
	}
}
